package com.hankol.community.viewmodel

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.*
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import com.baselibrary.*
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.*
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.ClickExpandListener
import com.baselibrary.view.share.SharePopupWindow
import com.baselibrary.activity.BaseActivity
import com.baselibrary.utils.ShareManager
import com.hankol.community.R
import com.hankol.community.SelectFriendShareActivity
import com.hankol.community.ShareFriendActivity
import com.hankol.community.VideoDetailsActivity
import com.hankol.community.api.CommunityConstant
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.clientTimeline2SelectSendFriend2Bean
import com.hankol.community.databinding.FragmentVideoDetailsBinding
import com.hankol.community.databinding.PopupCommentlistBinding
import com.hankol.community.fragment.VideoDetailsFragment
import com.hankol.community.respository.CommunityRequestManager
import com.liaoinstan.springview.utils.DensityUtil
import com.media.publish.upload.impl.TVCUtils
import com.okhttp.SendRequest
import com.okhttp.callbacks.StringCallback
import com.okhttp.comment.CommentBean
import com.okhttp.comment.CommentReplyBean
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.rtmp.ITXVodPlayListener
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXVodPlayer
import okhttp3.Request
import org.json.JSONException
import kotlin.math.roundToLong


/**
 * @author: 关忆北、
 * @date: 2022/4/8
 * @Des：
 */
class VideoDetailsViewModel : BaseViewModel() {
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()
    var videoDetailsLD: MutableLiveData<VideoReadBean.DataBeanX> = MutableLiveData()
    var dynamicVideoLiveData: MutableLiveData<TimelineInfoData.ClientTimeline> = MutableLiveData()
    var historyAddLD: MutableLiveData<Any> = MutableLiveData()
    val UP_PLAYER = 200

    private var videoProgress: Long = 0
    private var videoDuration: Long = 0

    //推荐视频列表
    fun reqVideoDetails(context: Context, cursor: String, currentId: Long, btype: Long, bid: String) {
        TVCUtils.getDevUUID(context)?.let {
            val instance = CommunityRequestManager.getInstance()
            if (btype == 1L || btype == 3L || btype == 4L || btype == 5L) { //bid 推荐模型 bid 酒窖/话题/圈子/我的发布 必传
                instance.reqVideoDetails(videoDetailsLD, cursor, currentId, btype, bid, it)
            } else {
                instance.reqVideoDetails(videoDetailsLD, cursor, currentId, btype, it)
            }
        }
    }

    //标记推荐视频已读
    fun reqVideoHistoryAdd(busiId: Long) {
        CommunityRequestManager.getInstance().reqVideoHistoryAdd(historyAddLD, busiId)
    }

    fun reqDynamicVideoDetails(dynamicId: Long) {
        CommunityRequestManager.getInstance().reqDynamicDetails(dynamicVideoLiveData, dynamicId)
    }

    fun reqCommentList(page: Int, typeId: Long, topCommentId: Long) {
        CommunityRequestManager.getInstance().reqCommentList(commentListLiveData, page, CommentEnum.COMMENT_DYNAMIC.commentType, typeId, 0, topCommentId)
    }

    fun openCommentView(f: VideoDetailsFragment, viewListener: View.OnClickListener): PopupCommentlistBinding {
        val mPopupBinding = DataBindingUtil.bind<PopupCommentlistBinding>(LayoutInflater.from(f.context).inflate(R.layout.popup_commentlist, null))
        mPopupBinding!!.llVideoCommentHead.visibility = View.VISIBLE
        mPopupBinding.llPopupContent.setOnClickListener(f)
        mPopupBinding.tvPopupContent.setOnClickListener(f)
        mPopupBinding.tvPopupSend.setOnClickListener(f)
        f.activity?.let { openComment(it, mPopupBinding, f) }
        mPopupBinding.BaseCommentView.setEmptyViewListener(viewListener)
        return mPopupBinding
    }

    fun createCommentPop(activity: VideoDetailsActivity, binding: PopupCommentlistBinding, mBinding: FragmentVideoDetailsBinding): PopupWindow {
        return activity.communityHelp.showCommentPop(activity, binding.root, mBinding.llBottom, Gravity.BOTTOM)
    }

    fun getStrAt(atMembers: List<TimelineInfoData.AtMembersBean>?): String {
        return if (atMembers.checkNotNull()) {
            val mBuffer = StringBuffer()
            if (atMembers != null) {
                for (atMember in atMembers) {
                    mBuffer.append("@" + atMember.name).append("  ")
                }
            }
            mBuffer.toString()
        } else {
            ""
        }
    }

    @SuppressLint("SetTextI18n")
    fun setView(mBinding: FragmentVideoDetailsBinding, it: TimelineInfoData.ClientTimeline, tHandler: Handler, mVodPlayer: TXVodPlayer, activity: Activity) {
        mBinding.ivDetailsHead.setData(it.user.icon, it.user.isFans == 1)
        mBinding.ivDetailsFollow.visibility = when (it.user.id) {
            SpUtils.getInstance().userId -> View.GONE
            else -> View.VISIBLE
        }
        mBinding.tvDetailsName.paint.isFakeBoldText = true
        mBinding.ivDetailsFollow.isSelected = it.user.isFocusFans
        mBinding.tvDetailsName.text = "@${SpanUtils.appendEllipsis(it.user.name, 9)}"
        if (it.content.checkNotNull()) {
            mBinding.tvDetailsDes.visibility = View.VISIBLE
            mBinding.tvDetailsDes.setText(it.content)
            mBinding.tvDetailsDes.setListener(object : ClickExpandListener {
                override fun click() {
                    mBinding.svContent.visibility = View.VISIBLE
                    mBinding.tvDetailsDesExpand.text = it.content
                    mBinding.tvDetailsDes.visibility = View.GONE
                }
            })
            mBinding.tvDetailsCollapse.setOnClickListener {
                mBinding.tvDetailsDes.visibility = View.VISIBLE
                mBinding.tvDetailsDes.toggleCollapsed()
                mBinding.svContent.visibility = View.GONE
            }

        } else {
            mBinding.tvDetailsDes.visibility = View.GONE
        }
        cutHeight(activity)
        mBinding.ivDetailsGive.isLiked = it.isSupported
        mBinding.ivDetailsCollection.isLiked = it.isFavorited
        mBinding.ivDetailsInterval.text = TimeUtil.fromToday(it.ctime)
        mBinding.tvDetailsLocation.text = if (!CommonUtil.isBlank(it.address)) it.address else ""
        mBinding.tvDetailsShare.text = NumberUtils.formatBigNum((it.forwardNum + it.outForwardNum).toString())
        mBinding.tvDetailsGive.text = if (it.supportNum > 0) NumberUtils.formatBigNum(it.supportNum.toString()) else "赞"
        mBinding.tvDetailsLike.text = if (it.favoriteNum > 0) NumberUtils.formatBigNum(it.favoriteNum.toString()) else "收藏"
        mBinding.tvDetailsCommentNum.text = if (it.commentNum > 0) NumberUtils.formatBigNum(it.commentNum.toString()) else "抢首评"

        mBinding.llDetailsLocation.visibility = if (it.address.isBlank()) View.GONE else View.VISIBLE
        if (it.tags.isNotEmpty()) {
            mBinding.tvDetailsTopic.text = "#${it.tags[0]}"
            mBinding.tvDetailsTopic.visibility = View.VISIBLE
        } else {
            mBinding.tvDetailsTopic.visibility = View.GONE
        }
        if (it.showType == 4) { //转发的视频
            mBinding.tvDetailsName.text = "@${it.user.name}"
        }
        val url = if (it.showType == 2) it.video else it.forwardTimeline.video
        initPlayerView(activity, url, tHandler, mVodPlayer, mBinding)
    }


    private fun initPlayerView(context: Context, url: String, tHandler: Handler, mVodPlayer: TXVodPlayer, mBinding: FragmentVideoDetailsBinding) {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showShort(context, "视频链接出错")
            return
        }
        mBinding.tvvDetailsView.setLogMargin(12f, 12f, 110f, 60f)
        mBinding.tvvDetailsView.showLog(false)
        mBinding.tvvDetailsView.keepScreenOn = true
        mVodPlayer.setVodListener(object : ITXVodPlayListener {
            override fun onPlayEvent(txVodPlayer: TXVodPlayer, event: Int, param: Bundle) {
                when (event) {
                    TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED -> {
                        mBinding.pbLoading.visibility = View.GONE
                        mBinding.ivDetailsPlay.isSelected = true
                    }
                    TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME -> {
                    }
                    TXLiveConstants.PLAY_EVT_PLAY_END -> {
                        mVodPlayer.seek(0)
                        mVodPlayer.resume()
                    }
                    TXLiveConstants.PLAY_EVT_PLAY_PROGRESS -> {
                        val progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS)
                        val duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS)
                        mBinding.sbDetailsDpeed.progress = progress
                        mBinding.sbDetailsDpeed.max = duration
                        videoProgress = progress.toLong()
                        videoDuration = duration.toLong()
                    }
                    else -> {
                    }
                }
                if (event < 0) // 播放点播文件失败
                    mVodPlayer.stopPlay(true)
            }

            override fun onNetStatus(txVodPlayer: TXVodPlayer, bundle: Bundle) {}
        })
        mVodPlayer.setPlayerView(mBinding.tvvDetailsView)
        mVodPlayer.setAutoPlay(true)
        mVodPlayer.enableHardwareDecode(false) // 是否使用硬解码
        mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT) // player 渲染角度
        mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION)
        val result: Int = mVodPlayer.startVodPlay(url)
        if (result == 0) {
            mBinding.ivDetailsPlay.isSelected = true
            hidePlayerView(tHandler)
        }
        mBinding.ivDetailsPlay.setOnClickListener { v: View? ->
            hidePlayerView(tHandler)
            if (mVodPlayer.isPlaying) {
                mVodPlayer.pause()
                mBinding.ivDetailsPlay.isSelected = false
            } else {
                mVodPlayer.resume()
                mBinding.ivDetailsPlay.isSelected = true
            }
        }

    }


    fun setNameTVMaxWidth(activity: Activity, mBinding: FragmentVideoDetailsBinding): Int {
        val marginSum = ScreenUtils.marginSum(activity, 14, 12, 11, 16)
        return ScreenUtils.getUserNameMaxWidth(activity, marginSum, mBinding.llTools, mBinding.ivDetailsInterval)
    }

    fun hidePlayerView(tHandler: Handler) {
        tHandler.removeMessages(UP_PLAYER)
        tHandler.sendEmptyMessageDelayed(UP_PLAYER, 3000)
    }


    fun addComment(type: Int, typeId: Int, edContent: TextView, activity: Activity, listener: OnPublishCompleteListener?) {
        val content = edContent.text.toString().trim()
        if (CommonUtil.isBlank(content)) {
            ToastUtils.showShort(activity, "请输入")
            return
        }
        SendRequest.commentAdd(SpUtils.getInstance().userToken, SpUtils.getInstance().userId, type, typeId, content, object : StringCallback() {
            override fun onBefore(request: Request, id: Int) {
                super.onBefore(request, id)
                LoadingManager.showLoadingDialog(activity, null)
            }

            override fun onAfter(id: Int) {
                super.onAfter(id)
                LoadingManager.hideLoadingDialog(activity)
            }

            override fun onError(call: okhttp3.Call, e: Exception, id: Int) {}
            override fun onResponse(response: String, id: Int) {
                try {
                    val mCommentReplyBean = GsonUtils.parseJsonToBean(response, CommentReplyBean::class.java)
                    if (mCommentReplyBean != null && mCommentReplyBean.isSuccess) {
                        edContent.text = ""
                        if (mCommentReplyBean.data.getRewardScore() > 0) {
                            //发表评论
                            DialogManager.showCoinDialog(activity, "评论成功", mCommentReplyBean.data.getRewardScore())
                            reqUpUserInfo()
                        }

                        listener?.onPublishComplete(mCommentReplyBean)
                        KeyBoardUtils.hideShowKeyboard(activity)
                    } else {
                        ToastUtils.showShort(activity, mCommentReplyBean.msg)
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        })
    }

    /**
     * 更新收藏状态
     */
    fun upCollectionState(data: TimelineInfoData.ClientTimeline?, mBinding: FragmentVideoDetailsBinding) {
        data?.apply {
            mBinding.ivDetailsCollection.isEnabled = true
            favoriteNum = if (isFavorited) {
                //说明是取消点赞
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "取消收藏")
                favoriteNum.minus(1)
            } else {
                //说明是进行点赞
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "收藏成功")
                favoriteNum.plus(1)
            }
            isFavorited = !isFavorited
            mBinding.ivDetailsCollection.isLiked = isFavorited

            mBinding.tvDetailsLike.text = if (favoriteNum > 0) NumberUtils.formatBigNum(favoriteNum.toString()) else "收藏"
            if (favoriteNum < 0) favoriteNum = 0//避免出现负数

            EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_collect_status, data.id.toInt())
        }
    }

    /**
     * 更新点赞状态
     */
    fun upSupportedState(data: TimelineInfoData.ClientTimeline?, mBinding: FragmentVideoDetailsBinding): Boolean {
        data?.apply {
            mBinding.ivDetailsGive.isEnabled = true
            supportNum = if (isSupported) {
                //原始值是true 则表示是取消操作
                supportNum.minus(1)
            } else {
                supportNum.plus(1)
            }
            isSupported = !isSupported
            mBinding.ivDetailsGive.isLiked = isSupported
            mBinding.tvDetailsGive.text = if (supportNum > 0) NumberUtils.formatBigNum(supportNum.toString()) else "收藏"
            if (supportNum < 0) supportNum = 0//避免出现负数

            EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_like_status, data.id.toInt())
            return isSupported
        }
        return false

    }


    fun openComment(activity: Activity, mPopupBinding: PopupCommentlistBinding, listener: OnRefreshLoadMoreListener) {
        //弹窗Popup
        val mSpringPopup: SmartRefreshLayout = mPopupBinding.smartComment

        val linearParams = mPopupBinding.BaseCommentView.layoutParams as LinearLayout.LayoutParams
        linearParams.height = cutHeight(activity)
        mPopupBinding.BaseCommentView.layoutParams = linearParams
        mPopupBinding.BaseCommentView.setEmptyImgSize(DensityUtil.dip2px(activity, 200f), DensityUtil.dip2px(activity, 200f))
        mSpringPopup.setOnRefreshLoadMoreListener(listener)
        mPopupBinding.BaseCommentView.setAdapter(activity, null)

        mPopupBinding.BaseCommentView.visibility = View.GONE
        mPopupBinding.PBarSldComment.visibility = View.VISIBLE

    }


    fun share(data: TimelineInfoData.ClientTimeline, activity: BaseActivity, communityHelp: CommunityHelp): SharePopupWindow? {
        var mVideoUrl = ""
        val shareUrl = Constants.DYNAMIC_SHARE_URL + data.id
        if (data.showType == 2) { //视频
            mVideoUrl = data.video
        } else if (data.showType == 4) { //转发的视频
            if (data.forwardTimeline != null) {
                if (data.forwardTimeline.showType == 2) {
                    mVideoUrl = data.forwardTimeline.video
                }
            }
        }
        val title = if (data.content.checkNotNull()) data.content else "@${data.user.name}发了一个视频，快点开来看看！"
        val des = if (data.content.checkNotNull()) data.content else " "
        val showShare = ShareManager.showSharePopWindow(activity, shareUrl, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {
            override fun onShareClick(type: Int) {
                when (type) {

                    ShareItemBean.WXZone, ShareItemBean.WX -> {
                        reqAddShareNum(data.id)
                    }

                    ShareItemBean.DOWN -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                VideoDownloadUtil.download(activity, mVideoUrl, ".mp4")
                            }
                        })
                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                LoadingManager.showLoadingDialog(activity)
                                val sharePosterBean: SharePosterBean = changePosterBean(data)
                                sharePosterBean.imagePaths = ArrayList()
                                for (i in 0..2) {
                                    val posterStyle = PosterStyle(activity, sharePosterBean, i) { path: String? ->
                                        sharePosterBean.imagePaths.add(path)
                                        checkListSize(activity, sharePosterBean)
                                    }
                                    posterStyle.startDraw()
                                }
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        val intent = Intent()
                        val bundle = Bundle()
                        bundle.putInt("type", 3)
                        bundle.putInt("id", data.id.toInt())
                        bundle.putInt("complaintUserId", data.user.id.toInt())
                        intent.putExtras(bundle)
                        activity.openActivity(communityHelp.getJuBaoOneActivity(), bundle)

                    }
                }
            }

            fun checkListSize(activity: Activity, sharePosterBean: SharePosterBean) {
                if (sharePosterBean.imagePaths.size == 3) {
                    LoadingManager.hideLoadingDialog(activity)
                    val bundle = Bundle()
                    bundle.putSerializable(Constants.SHARE_POSTER_BEAN, sharePosterBean)
                    ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER_SELECT, bundle)
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", clientTimeline2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", clientTimeline2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }
            }

        })
        showShare?.setShareItem(true, false, true)
        return showShare
    }

    fun changePosterBean(data: TimelineInfoData.ClientTimeline): SharePosterBean {

        val sharePosterBean = SharePosterBean(2)
        sharePosterBean.userAvatar = data.user.icon
        sharePosterBean.userName = data.user.name
        sharePosterBean.shareImage = data.cover
        sharePosterBean.shareContent = data.content
        sharePosterBean.atPersonName = getStrAt(data.atMembers)
        sharePosterBean.isVideo = data.showType == 2
        sharePosterBean.isFans = data.user.isFans == 1
        sharePosterBean.isWinnery = data.user.isWinery != 0
        return sharePosterBean
    }


    fun cutHeight(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm)
        val mScreenHeight = dm.heightPixels // 屏幕高度（像素）z
        return mScreenHeight / 2
    }

    fun sensorsFollow(sponsorUser: UserInfo?, bean: TimelineInfoData.SimpleUser) {
        sponsorUser?.data?.let {
            SensorsDataManager.instance.attention(it.name, it.id.toString(), bean.name, bean.id.toString(), CommunityConstant.DYNAMIC_POINT, true)
        }
    }

    fun sensorsVideo(activity: VideoDetailsActivity, data: TimelineInfoData.ClientTimeline) {

        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.browseDynamic(data.tagCategoryName, activity.sourceName, subString(data.content), getStateType(data.recommendType), "视频动态", if (data.tags.checkNotNull()) data.tags[0] else "", videoComputing((videoProgress / 1000).toDouble(), (videoDuration / 1000).toDouble()))
            if (data.wineryCode != 0L) {//酒窖发布的动态
                SensorsDataManager.instance.cellarDynamicSee(data.wineryName.checkValue())
            }
        }
    }

    /**
     * 计算视频百分比
     */
    private fun videoComputing(speedNum: Double, totalNum: Double): Long {
        try {
            if (speedNum == totalNum) return 100
            return ((speedNum / totalNum) * 100).roundToLong()
        } catch (num: NumberFormatException) {
            //防止异常情况
            return 0
        }
    }

    fun subString(content: String): String {
        if (!content.checkNotNull()) return ""
        if (content.length > 12) {
            return content.substring(0, 12)
        }
        return content
    }

    private fun getStateType(remark: Int): String {
        return when (remark) {
            TimelineInfoData.ClientTimeline.RECOMMEND_TYPE -> {
                "推荐动态"
            }
            TimelineInfoData.ClientTimeline.TOPPING_TYPE -> {
                "置顶动态"
            }
            else -> {
                "普通动态"
            }
        }
    }

    interface OnPublishCompleteListener {
        fun onPublishComplete(bean: CommentReplyBean)
    }
}
